package com.swg.wxorder.controller;

import com.swg.wxorder.entity.ProductCategory;
import com.swg.wxorder.entity.ProductInfo;
import com.swg.wxorder.result.ResultVOUtil;
import com.swg.wxorder.service.CategoryService;
import com.swg.wxorder.service.ProductService;
import com.swg.wxorder.vo.ProductCategoryVo;
import com.swg.wxorder.vo.ProductInfoVo;
import com.swg.wxorder.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 【swg】.
 * @Date 2018/6/23 10:38
 * @DESC
 * @CONTACT 317758022@qq.com
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;


    @RequestMapping("/list")
    public ResultVo<ProductCategoryVo> list(){
        //1. 查询所有上架商品
        List<ProductInfo> productInfoList = productService.findAllUpProducts();

        //2. 根据所有上架商品查询所有的类目
        List<Integer> categoryType = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());
        List<ProductCategory> categoryList = categoryService.productCategoryListByType(categoryType);
        for(ProductCategory productCategory:categoryList){
            System.out.println(productCategory.getCategoryName());
        }

        //3. 进行数据拼装返回给前端
        List<ProductCategoryVo> productCategoryVoList = new ArrayList<>();
        for(ProductCategory productCategory:categoryList){
            ProductCategoryVo productCategoryVo = new ProductCategoryVo();
            productCategoryVo.setCategoryName(productCategory.getCategoryName());
            productCategoryVo.setCategoryType(productCategory.getCategoryType());
            List<ProductInfoVo> productInfoVoList = new ArrayList<>();
            for(ProductInfo productInfo:productInfoList){
                if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVo productInfoVo = new ProductInfoVo();
                    BeanUtils.copyProperties(productInfo,productInfoVo);
                    productInfoVoList.add(productInfoVo);
                }
            }
            productCategoryVo.setProductInfoVoList(productInfoVoList);
            productCategoryVoList.add(productCategoryVo);
        }

        return ResultVOUtil.success(productCategoryVoList);
    }

}
